package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private UserService userService;
    @Reference
    private MenuService menuService;

    @RequestMapping("/findMenuPermission")
    //查询当前用户所有查看的菜单权限:
    public Result findMenuPermission() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前登录用户的用户名:
        String username = user.getUsername();
        //根据用户名查询对应的菜单:
        List<Menu> menuList = userService.findMenuByUsername(username);

        if (menuList == null || menuList.size() <= 0) {
            return new Result(false, "查询展示侧边栏菜单失败");
        }
        return new Result(true, "查询展示侧边栏菜单成功", menuList);
    }

    @RequestMapping("findall")
    public Result findall() {
        List<Menu> menus = menuService.findall();
        return new Result(true, "查询菜单成功", menus);
    }

    @RequestMapping("findMenuByRoleId")
    public Result findMenuByRoleId(int id) {
        try {
            List<Integer> ids = menuService.findMenuByRoleId(id);
            return new Result(true, "回显菜单成功", ids);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "回显菜单失败");
        }
    }
}
